package com.ptswitch.material.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hxzon.util.MD5Util;
import org.hxzon.util.StringUtil;
import org.hxzon.util.cache.FifoCache;
import org.springframework.stereotype.Service;

import com.ptswitch.material.dao.impl.UserDao;
import com.ptswitch.material.model.common.Uzer;
import com.ptswitch.material.service.UserService;

@Service
public class UserServiceImpl implements UserService {
    private FifoCache<String, Uzer> userCache = new FifoCache<String, Uzer>(100);
    @Resource
    protected UserDao userDao;

    public Uzer findById(String id) {
        Uzer result = userDao.findById(id);
        if (result != null) {
            userCache.add(result.getUsername(), result);
        }
        return result;
    }

    public Uzer findByUsername(String username) {
        if (username == null || username.isEmpty()) {
            return null;
        }
        if (Uzer.Username_Guess.equals(username)) {
            return null;//return null not return new Uzer()
        }
        Uzer result = userCache.get(username);
        if (result != null) {
            return result;
        }
        username = StringUtil.escapeSql(username);
        result = userDao.findByUsername(username);
        if (result != null) {
            userCache.add(result.getUsername(), result);
        }
        return result;
    }

    public Uzer findByUsernameAndPassword(String username, String password) {
        if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
            return null;
        }
        if (password.length() < 32) {
            password = MD5Util.toMD5(username + password);
        }
        Uzer result = findByUsername(username);
        if (result != null) {
            if (password.equals(result.getPassword())) {
                return result;
            }
        }
        return null;
    }

    public boolean isAdmin(String username) {
        Uzer user = findByUsername(username);
        return user != null && user.getAdminGrade() == 0;
    }

    public boolean isAdmins(String username) {
        Uzer user = findByUsername(username);
        return user != null && user.getAdminGrade() <= 1;
    }

    public List<Uzer> findByDepartment(int department) {
        return userDao.findByDepartment(department);
    }

    public boolean existUsername(String username) {
        return (findByUsername(username) != null);
    }

    @Override
    public List<Uzer> findAll() {
        return userDao.findAll();
    }

    @Override
    public long countAll() {
        return userDao.countAll();
    }

    public void save(Uzer user) {
        userDao.save(user);
        userCache.add(user.getUsername(), user);
    }

    public void delete(Uzer user) {
        userDao.delete(user);
        userCache.remove(user.getUsername());
    }
}
